package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class PublishListener {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    @PostConstruct // 实例化后自动执行该方法
    public void init() {
        // 开启线程执行任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 开启redisson队列的监听
                RBlockingQueue<String> queue = redissonClient.getBlockingQueue("article-publish");
                // 启动时发送一条初始化消息,用于通道的建立
                // 创建延迟队列
                RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(queue);
                // 使用延迟队列发送延迟消息 参数  消息  延迟时间  时间单位
                delayedQueue.offer("init", 1, TimeUnit.SECONDS);
                try {
                    while (true) {
                        String poll = queue.poll(30, TimeUnit.SECONDS);
                        if (!StringUtils.isEmpty(poll) && !poll.equals("init")) {
                            System.out.println("接收到消息: " + poll + " ,时间为: " + new Date());
                            // 转换成文章对象
                            WmNews wmNews = JSON.parseObject(poll, WmNews.class);
                            // 重新进入审核流程
                            auditService.audit(wmNews);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
